package cn.wsalix.finance.service.impl;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.anlaser.service.impl.SimpleServiceImpl;
import cn.anlaser.utils.SearchFilter;
import cn.anlaser.utils.SearchFilter.Operator;
import cn.wsalix.finance.entity.Bank;
import cn.wsalix.finance.entity.CreditCard;
import cn.wsalix.finance.entity.Customer;
import cn.wsalix.finance.form.CreditCardForm;
import cn.wsalix.finance.repository.CreditCardRepository;
import cn.wsalix.finance.service.BankService;
import cn.wsalix.finance.service.CreditCardService;
import cn.wsalix.finance.service.CustomerService;

@Service("creditCardService")
public class CreditCardServiceImpl extends
		SimpleServiceImpl<CreditCardForm, CreditCardRepository, CreditCard>
		implements CreditCardService {
	@Autowired
	private CreditCardRepository creditCardRepository;
	@Autowired
	private CustomerService customerService;
	@Autowired
	private BankService bankService;
	@Override
	public String module() {
		return "/finance/credit_card";
	}

	@Override
	public CreditCardRepository getRepository() {
		return creditCardRepository;
	}

	@Override
	public Class<CreditCard> getEntityClazz() {
		return CreditCard.class;
	}

	@Override
	public Map<String, SearchFilter> buildByForm(CreditCardForm form) {
		Map<String, Object> searchParams = new HashMap<String, Object>();
		Map<String, SearchFilter> filters = SearchFilter.parse(searchParams);
		if (form.getCustomerId() != null && form.getCustomerId() != 0) {
			filters.put("customer.id", new SearchFilter("customer.id",
					Operator.EQ, form.getCustomerId()));
		}
		if (form.getName() != null && !form.getName().equals("")) {
			filters.put("name",
					new SearchFilter("nama", Operator.EQ, form.getName()));
		}

		return filters;
	}

	@Override
	public CreditCard add(CreditCardForm form) {
		if (form.getCustomerId() != null && form.getCustomerId() != 0) {
			Customer customer = customerService.findById(form.getCustomerId());
			form.setCustomer(customer);
		}	
		if (form.getBankId() != null && form.getBankId() != 0) {
			Bank bank = bankService
					.findById(form.getBankId());
			form.setBank(bank);
		}
		return super.add(form);
	}

	@Override
	public CreditCard edit(CreditCardForm form) {
		if (form.getCustomerId() != null && form.getCustomerId() != 0) {
			Customer customer = customerService.findById(form.getCustomerId());
			form.setCustomer(customer);
		}	
		if (form.getBankId() != null && form.getBankId() != 0) {
			Bank bank = bankService
					.findById(form.getBankId());
			form.setBank(bank);
		}
		return super.edit(form);
	}

}
